package cn.biplam.front.upload;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.Log;
import cn.biplam.common.client.Operator;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.client.Log.Log_Level;
import cn.biplam.common.opcode.SysManageCode.FileUploadOptCode;
import cn.biplam.common.paramters.SysName;
import cn.biplam.common.struc.SysStruc.FileUpLoadStru;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.front.Index;
import cn.biplam.front.html.HtmlFile;
import cn.biplam.front.html.HtmlForm;
import cn.biplam.front.html.HtmlPage;
import cn.biplam.front.html.HtmlForm.Form_Type;
import cn.biplam.front.html.base.HtmlMeta;
import cn.biplam.front.html.base.Const.Window_Event;
import cn.biplam.front.html.base.HtmlMeta.Templet_Type;
import cn.biplam.front.htmlscript.HtmlScript;
import cn.biplam.front.htmlscript.script.ScriptBind;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * 文件上传服务类
 * IFrame获取页面提交到doGet,绘制Form传回客户端,Form的提交地址为本服务类的Post端口
 * 处理成功后,将文件在上传文件信息数据库表中的主键ID,回调设置到FiltUpLoad页面对象的HtmlValue中
 * 实际使用时,调用FiltUpLoad模板即可
 * @author 	WangSong 2009-6-13 下午06:46:56
 * @version 1.0
 */
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = -980500768379178654L;
	private ServletConfig config;
	/**文件限制大小*/
	private static long limitsize=0;
	/**上传文件目录*/
	private static String path=null;
	private final String ID="upform";

	/**
	 * 保存Servlet config属性,供SmartUpload使用
	 * @param config
	 * @throws ServletException
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}

	/**
	 * 文件上传客户端页面响应接口
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String sHomeUrl=request.getContextPath();
			HtmlPage page = new HtmlPage("UpLoad");
			page.importMeta(new HtmlMeta(Templet_Type.Templet_Charset));
			page.importScript(new HtmlScript("/Js/default.js",sHomeUrl));
			page.importScript(new HtmlScript("/Js/ajx.js",sHomeUrl));
			page.importScript(new HtmlScript("/Js/upload.js",sHomeUrl));

			/**创建客户端上传表单**/
			String parentID=request.getParameter("id");//父窗口上传控件ID
			HtmlForm form=new HtmlForm(this.ID);
			form.setType(Form_Type.MultiData);
			form.setTarget(sHomeUrl+SysName.UpLoadPort+"?parentID="+parentID);
			HtmlFile input=new HtmlFile(ID+"1");	//创建文件Input
			input.bind(Window_Event.OnPropertyChange, "setName(this,'"+parentID+"');");
			form.put(input);

			page.put(form);

			response.setContentType("text/html"); 
			PrintWriter out = new PrintWriter (response.getOutputStream());
			out.print(page.draw());
			out.close();
		} catch (ErrorMessage e) {
			Index.printError(request, response, e);
		}
	}

	/**
	 * 文件上传服务响应接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		StringBuilder dataId=new StringBuilder();//文件存储后的数据库ID
		StringBuilder sb=new StringBuilder();
		String filePath;
		String fileName;
		String userID="";
		String parentID=request.getParameter("parentID");//父窗口上传控件ID
		StringBuilder message=new StringBuilder();//处理过程中的用于返回的信息
		try {
			if(limitsize==0){this.prePare(request, response);}//初始化参数(上传文件目录,文件限制大小)
			boolean success=true;

			SmartUpload mySmartUpload = new SmartUpload();
			mySmartUpload.initialize(config, request, response);

			/**开始上传处理*/
			mySmartUpload.upload();
			String fileid;
			filePath = TOOLS.createDailyDir(path);
			String namePrefix=TOOLS.getDailyFileName();
			/**处理多个文件*/
			for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
				/**处理每个文件*/
				com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
				if (!myFile.isMissing()) {
					if(myFile.getSize()>limitsize){
						success=false;
						message.append(myFile.getFileName());
						message.append(" size ");
						message.append(myFile.getSize());
						message.append(" is greater than limitsize:");
						message.append(limitsize/(1024*1024));
						message.append("M.");
						continue;
					}
					fileName=namePrefix+myFile.getFileName();
					myFile.saveAs(filePath+fileName,SmartUpload.SAVE_PHYSICAL);

					DataFilter filter= new DataFilter();
					filter.put(FileUpLoadStru.FILE_NAME, fileName);
					filter.put(FileUpLoadStru.FILE_PATH, filePath);
					OperatorResult result = Operator.get(FileUploadOptCode.Insert_File, userID, filter);
					fileid=result.getLastRowId();
					
					if(dataId.length()>0){
						dataId.append(",");
					}
					dataId.append(fileid);
				}
			}

			/**以下代码处理页面返回*/
			sb.append("<script>parent.uploadSetID('");
			sb.append(parentID);
			sb.append("','");
			
			if (dataId.length()>0 && success)
				sb.append(dataId.toString());
			else{//处理不成功
				sb.append("0,");
				if(!success){	//文件大小不符合
					sb.append(message);
				}else{
				}
			}
			sb.append("');</script>");
		}catch (SmartUploadException e) {
			ErrorMessage me = new ErrorMessage(e);
			Index.printError(request, response, me);
		}catch (ErrorMessage e) {
			sb.delete(0, sb.length());
			sb.append("<script>");
			sb.append("parent.");
			sb.append(ScriptBind.Alert("FileUpLoad", ScriptBind.getAlertInfo(e)));
			sb.append("</script>");
			Log.write(e,Log_Level.Error);
		}
		response.setContentType("text/html;charset=GBK");
		PrintWriter out = response.getWriter();
		out.print(sb.toString());
		out.flush();
		out.close();
	}

	/**
	 * 从配置属性文件初始化参数
	 * @param request
	 * @param response
	 * @throws ErrorMessage 
	 * @throws NumberFormatException 
	 */
	private void prePare(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ErrorMessage{
		limitsize = Long.parseLong(TOOLS.getValueByPropertyName(SysName.PropertiesPath, "UploadLimitSize"))*1024*1024;
		path = TOOLS.getValueByPropertyName(SysName.PropertiesPath, "UploadPath");
	}

}